<button class="btn btn-info btn-xs" data-toggle="modal" data-target="#taskImport{{ $id }}">导入资源</button>

<div class="modal fade" id="taskImport{{ $id }}" tabindex="-1" role="dialog" aria-labelledby="taskImport"
     aria-hidden="true">
    <div class="modal-dialog modal-mixed">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true" style="font-size: 36px;">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">导入资源 (<a href="/task_import_template.xlsx" target="_blank"
                                                                       style="font-size:12px">下载导入模板</a>)</h4>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="exampleFormControlInput1" class="form-label">资源文件</label>
                    <form id="uploadForm">
                        <input type="file" name="taskFile" id="fileInput" class="form-control">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}"/>
                    </form>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="taskImport({{ $id }})">提交</button>
            </div>
        </div>
    </div>
</div>
<div id="result{{ $id }}"></div>
<script>
    function taskImport(id) {
        var formData = new FormData();
        var fileInput = $('#fileInput')[0]; // 获取文件输入元素
        var file = fileInput.files[0]; // 获取第一个文件
        formData.append('file', file); // 将文件添加到FormData对象中
        formData.append('id', id);
        formData.append('_token', $("input[name='_token']").val());

        $.ajax({
            url: '/admin/ajax/taskImport', // 服务器端处理文件上传的脚本URL
            type: 'POST',
            data: formData,
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            processData: false, // 告诉jQuery不要处理发送的数据
            success: function (response) {
                if (response.code == -1) alert(response.message);
                $('#result' + id).html('文件上传成功 '); // 显示错误信息
                window.location.href = '/admin/task/';
            },
            error: function (xhr, status, error) {
                $('#result').html('文件上传失败: ' + error); // 显示错误信息
            }
        });
    }
</script>
